package com.lucien.framework.web.chat;


import com.alibaba.fastjson.JSONObject;
import com.lucien.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessageSendingOperations;
import org.springframework.stereotype.Service;

@Service
public class ChatService {

    @Autowired
    private SimpMessageSendingOperations operations;


    /**
     * convertAndSend 群发
     * convertAndSendToUser 单发  单发会在主题前拼接/user
     *
     * @param msg
     * @return
     */
    public boolean sendMsg(String msg) {
        try {
            JSONObject msgJson = JSONObject.parseObject(msg);
            if (StringUtils.isNotNull(msgJson.getString("groupId")) &&
                    msgJson.getString("messageTypeId").equals("2")) {
                operations.convertAndSend("/topic/chatroom", msgJson);

            }
            else if (msgJson.getString("toName").equals("all") &&
                    msgJson.getString("messageTypeId").equals("2")) {
                operations.convertAndSend("/topic/chatroom", msgJson);

            } else if (msgJson.getString("toName").equals("all") &&
                    msgJson.getString("messageTypeId").equals("1")) {
                System.out.println("chatservice=============用户上线信息");
                operations.convertAndSend("/topic/chatroom", msgJson);

            } else if (msgJson.getString("toName").equals("all") &&
                    msgJson.getString("messageTypeId").equals("3")) {
                operations.convertAndSend("/topic/chatroom", msgJson);

            }
            //单独给某个用户推送
            else if (!msgJson.getString("toName").equals("all") &&
                    msgJson.getString("messageTypeId").equals("2")) {
                operations.convertAndSendToUser(msgJson.getString("toName"), "/topic/touser", msgJson);
                //使用了touser 会拼接上 /user ，最终推送到 /user/topic/msg
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 用户上线下线消息
     * @param username
     * @return
     */
    public boolean userMsg(String username){


        return true;
    }

}
